package com.winit.openapi.apiadapter.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ups.spi.command.QueryWarehouseByTypesCommand;
import com.winit.ups.spi.sys.CustomerTansferConfigService;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * 仓库代码查询接口适配
 * <URL>http://developer.winit.com.cn/Index/index.php?s=Index/index/id
 * /12/l/zh-cn<URL> 由于目前ERP里面可以查询到比利时等已经迁仓的仓库信息，改接口暂时不开放
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2016年12月29日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class QueryWarehouseAdapteController extends AbstractAdapteController {

    private Logger                       logger = LoggerFactory.getLogger(QueryWarehouseAdapteController.class);

    @Resource
    private WarehouseService             upsWarehouseService;

    @Resource
    private CustomerTansferConfigService customerTansferConfigService;

    @RequestMapping(value = "/queryWarehouse")
    public String queryWarehouseList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        return doAdapte(requestMsg, responseMsg);

    }

    @Override
    protected void validateInputJson(RequestMsg requestMsg) {
//        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
//        if (null == json) {
//            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
//        }

    }

    @Override
    protected boolean checkCustomerTansferConfig(RequestMsg requestMsg, ResponseMsg responseMsg) {

        // 查询仓库没有入参，无法根据入参判断调用3E还是UPS。如果此处为true则调用UPS，否则调用3E
        return true;
    }

    @Override
    protected void doAdapteInOpenAPI(RequestMsg requestMsg, ResponseMsg responseMsg) {

        // Bpartner bpartner =
        // CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        // CustomerTansferConfigPkCommand command = new
        // CustomerTansferConfigPkCommand();
        // command.setCustomerCode(bpartner.getValue());
        // List<CustomerTansferConfigVo> configs =
        // customerTansferConfigService.queryCustomerTansferConfigs(command);
        //
        //
        // if (CollectionUtils.isNotEmpty(configs)) {
        // for (CustomerTansferConfigVo customerTansferConfigVo : configs) {
        // CodeCommand codeCommand = new CodeCommand();
        // codeCommand.setCode(customerTansferConfigVo.getWarehouseCode());
        // WarehouseVo warehouse =
        // upsWarehouseService.queryWarehouseByTypes(command);
        // result.add(warehouse);
        // }
        // }
        QueryWarehouseByTypesCommand command = new QueryWarehouseByTypesCommand();
        command.setCtx(CommandContext.getContext());
        // 使用发货仓查询
        command.setTypes(Arrays.asList("CONSIGNMENT"));
        List<WarehouseVo> result = upsWarehouseService.queryWarehouseByTypes(command);
        if (CollectionUtils.isEmpty(result)) {
            logger.warn("查询仓库代码失败.command：" + JSON.toJSONString(command));
            throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS);
        }
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (WarehouseVo warehouseVo : result) {
            Map<String, Object> map = new HashMap<String, Object>();
            StringBuffer address = new StringBuffer();
            map.put("warehouseID", warehouseVo.getWarehouseId());
            map.put("warehouseCode", warehouseVo.getCode());
            map.put("warehouseName", warehouseVo.getName());
            address.append(warehouseVo.getCountry())
                .append(",")
                .append(StringUtils.stripToEmpty(warehouseVo.getState()))
                .append(",")
                .append(StringUtils.stripToEmpty(warehouseVo.getCity()))
                .append(",")
                .append(StringUtils.stripToEmpty(warehouseVo.getPostal()))
                .append(",")
                .append(StringUtils.stripToEmpty(warehouseVo.getAddress()));
            map.put("warehouseAddress", address.toString());
            data.add(map);

        }
        responseMsg.setData(data);

    }

}
